<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 封装ajax异步请求
    function ajaxPromise(url) {
      // 1.创建请求对象
      let xhr = new XMLHttpRequest()

      // 2.打开请求
      xhr.open('GET', url, true) // true设置为异步

      // 3.配置请求
      // xhr.timeout = 3000
      // xhr.responseType = 'text'
      // xhr.setRequestHeader('cuifan', 'hello cuifan')

      // 4.发起请求
      xhr.send()

      return new Promise((resolve, reject) => {
        xhr.onreadystatechange = function() {
          if (this.readyState !== 4) return
            // 0表示未初始化 1 opened 2 接收完请求头 3 接收了部分响应体 4 全部接受完毕
          if (this.status >= 200 && this.status < 300) {
            resolve(this.response)
          } else {
            reject(new Error('请求失败:status:' + this.status))
          }
        }
      })
    }

    ajaxPromise('./00-stack.html').then(value => {
      console.log('请求体为：' + value);
    }).catch(reason => {
      console.log(reason.message);
    })
  </script>
</body>

</html>